import React, { useEffect, useState } from 'react';
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons';

import { editRulesContentApi } from '@/api/rulesWarningConfig';
import { equipmentProductListApi, equipmentProductDetailApi } from '@/api/equipmentProductApi';

interface TriggerCondition {
  id: string;
  productCode?: string;
  type?: string;
  fun?: string;
  condition?: string;
  val?: string;
  con?: 'or' | 'and';
}

interface TriggerTypeOption {
  label: string;
  value: string;
  triggerArr: Array<{ label: string; value: string }>;
}

interface TriggerRule {
  id: string;
  productCode?: string;
  conditions: TriggerCondition[];
  expression?: string;
  triggerTypeList: TriggerTypeOption[];
}

interface EditTriggerRulesDrawerProps {
  open: boolean;
  onClose: () => void;
  ruleId?: string;
  alarmRuleInfoId?: string;
  initialData?: {
    perfectMatchMode?: number;
    silencePeriod?: string;
    conditions?: Array<{
      id?: number;
      productCode?: string;
      conditionType?: string;
      conditionContent?: string;
    }>;
  };
  onSuccess?: (newRuleId?: string) => void;
}

const conditionOptions = [
  { label: '>', value: '>' },
  { label: '<', value: '<' },
  { label: '>=', value: '>=' },
  { label: '<=', value: '<=' },
  { label: '=', value: '==' },
  { label: '!=', value: '!=' },
];

const keysObj = {
  events: '设备事件触发',
  properties: '设备属性触发',
  services: '设备服务触发',
};
const keysArr = Object.keys(keysObj);

const EditTriggerRulesDrawer: React.FC<EditTriggerRulesDrawerProps> = ({
  open,
  onClose,
  ruleId,
  alarmRuleInfoId,
  initialData,
  onSuccess,
}) => {
  const [form] = AForm.useForm();
  const [loading, setLoading] = useState(false);
  const [productOptions, setProductOptions] = useState<
    Array<{ label: string; value: string; id: number }>
  >([]);
  const [triggerRules, setTriggerRules] = useState<TriggerRule[]>([
    {
      id: '1',
      triggerTypeList: [],
      conditions: [
        {
          id: '1',
          con: 'or',
        },
      ],
    },
  ]);

  // 获取产品列表
  const fetchProductList = async () => {
    try {
      const res = await equipmentProductListApi({
        page: 1,
        pageSize: 100,
      });

      if (res.success && res.data?.records) {
        const options = res.data.records.map((item: Record<string, unknown>) => ({
          label: item.productName as string,
          value: item.code as string,
          id: item.id as number, // 保存产品ID用于获取详情
        }));
        setProductOptions(options);
      }
    } catch (error) {
      console.error('获取产品列表失败:', error);
    }
  };

  // 获取产品详情和触发类型
  const fetchProductDetail = async (productCode: string, ruleId: string) => {
    try {
      // 根据productCode找到对应的产品ID
      const product = productOptions.find(p => p.value === productCode);
      if (!product) {
        console.error(
          'Product not found for code:',
          productCode,
          'Available products:',
          productOptions
        );
        return;
      }

      const res = await equipmentProductDetailApi({ id: product.id.toString() });
      if (res.success && res.data?.metaData) {
        // 解析metaData中的触发类型
        const metaData = JSON.parse(res.data.metaData as string) as Record<string, unknown>;

        const triggerTypeList: TriggerTypeOption[] = [];

        // 根据metaData构建触发类型列表（与旧代码保持一致）
        keysArr.forEach(key => {
          if (metaData[key] && Array.isArray(metaData[key])) {
            const triggerArr = (metaData[key] as Record<string, unknown>[]).map(
              (item: Record<string, unknown>) => ({
                label: (item.name as string) || (item.identifier as string),
                value: item.identifier as string,
              })
            );

            if (triggerArr && triggerArr.length > 0) {
              triggerTypeList.push({
                label: keysObj[key as keyof typeof keysObj],
                value: key,
                triggerArr,
              });
            }
          }
        });

        console.log('Generated triggerTypeList:', triggerTypeList);

        // 更新对应规则的触发类型列表
        setTriggerRules(prevRules =>
          prevRules.map(rule => {
            if (rule.id === ruleId) {
              console.log('Updating rule:', ruleId, 'with triggerTypeList');
              return { ...rule, triggerTypeList };
            }
            return rule;
          })
        );
      }
    } catch (error) {
      console.error('获取产品详情失败:', error);
    }
  };

  // 解析条件表达式（与旧代码逻辑保持一致）
  const parseConditionContent = (conditionContent: string): TriggerCondition[] => {
    if (!conditionContent) return [{ id: '1', con: 'or' }];

    const symbolArr = ['<=', '>=', '==', '!=', '>', '<'];
    const conditions: TriggerCondition[] = [];

    if (conditionContent.includes(' and ') || conditionContent.includes(' or ')) {
      // 处理多条件表达式
      const parts = conditionContent.split(/(\s*and\s*|\s*or\s*)/);
      let conditionIndex = 1;

      for (let i = 0; i < parts.length; i += 2) {
        const part = parts[i].trim();
        const logic = parts[i + 1] ? parts[i + 1].trim() : 'or';

        const symbol = symbolArr.find(s => part.includes(s));
        if (symbol) {
          const [left, right] = part.split(symbol);
          const [type, fun] = left.split('.');

          conditions.push({
            id: String(conditionIndex++),
            type: type?.trim(),
            fun: fun?.trim(),
            condition: symbol,
            val: right?.trim(),
            con: logic === 'and' ? 'and' : 'or',
          });
        }
      }
    } else {
      // 处理单条件表达式
      const symbol = symbolArr.find(s => conditionContent.includes(s));
      if (symbol) {
        const [left, right] = conditionContent.split(symbol);
        const [type, fun] = left.split('.');

        conditions.push({
          id: '1',
          type: type?.trim(),
          fun: fun?.trim(),
          condition: symbol,
          val: right?.trim(),
          con: 'or',
        });
      }
    }

    return conditions.length > 0 ? conditions : [{ id: '1', con: 'or' }];
  };

  // 初始化数据
  useEffect(() => {
    if (open) {
      fetchProductList();
      if (initialData) {
        form.setFieldsValue({
          perfectMatchMode: initialData.perfectMatchMode || 0,
          silencePeriod: initialData.silencePeriod || '',
        });

        // 转换现有条件数据
        if (initialData.conditions && initialData.conditions.length > 0) {
          const convertedRules = initialData.conditions.map((condition, index) => ({
            id: String(index + 1),
            productCode: condition.productCode,
            triggerTypeList: [],
            conditions: parseConditionContent(condition.conditionContent || ''),
            expression: condition.conditionContent,
          }));
          setTriggerRules(convertedRules);
        }
      }
    }
  }, [open, initialData, form]);

  // 当产品列表加载完成后，获取产品详情
  useEffect(() => {
    if (productOptions.length > 0 && initialData?.conditions) {
      initialData.conditions.forEach((condition, index) => {
        if (condition.productCode) {
          const ruleId = String(index + 1);
          fetchProductDetail(condition.productCode, ruleId);
        }
      });
    }
  }, [productOptions, initialData]);

  // 添加触发规则
  const addTriggerRule = () => {
    const newRule: TriggerRule = {
      id: String(Date.now()),
      triggerTypeList: [],
      conditions: [
        {
          id: '1',
          con: 'or',
        },
      ],
    };
    setTriggerRules([...triggerRules, newRule]);
  };

  // 删除触发规则
  const deleteTriggerRule = (ruleId: string) => {
    if (triggerRules.length <= 1) {
      window.$message.warning('至少需要保留一个触发规则');
      return;
    }
    setTriggerRules(triggerRules.filter(rule => rule.id !== ruleId));
  };

  // 添加条件
  const addCondition = (ruleId: string) => {
    setTriggerRules(
      triggerRules.map(rule => {
        if (rule.id === ruleId) {
          const newCondition: TriggerCondition = {
            id: String(Date.now()),
            con: 'or',
          };
          return {
            ...rule,
            conditions: [...rule.conditions, newCondition],
          };
        }
        return rule;
      })
    );
  };

  // 删除条件
  const deleteCondition = (ruleId: string, conditionId: string) => {
    setTriggerRules(
      triggerRules.map(rule => {
        if (rule.id === ruleId) {
          if (rule.conditions.length <= 1) {
            window.$message.warning('至少需要保留一个条件');
            return rule;
          }
          return {
            ...rule,
            conditions: rule.conditions.filter(condition => condition.id !== conditionId),
          };
        }
        return rule;
      })
    );
  };

  // 更新条件
  const updateCondition = (ruleId: string, conditionId: string, field: string, value: unknown) => {
    setTriggerRules(
      triggerRules.map(rule => {
        if (rule.id === ruleId) {
          return {
            ...rule,
            conditions: rule.conditions.map(condition => {
              if (condition.id === conditionId) {
                return { ...condition, [field]: value };
              }
              return condition;
            }),
          };
        }
        return rule;
      })
    );
  };

  // 更新规则产品
  const updateRuleProduct = (ruleId: string, productCode: string) => {
    setTriggerRules(
      triggerRules.map(rule => {
        if (rule.id === ruleId) {
          // 清空条件中的触发类型和功能
          const updatedConditions = rule.conditions.map(condition => ({
            ...condition,
            type: '',
            fun: '',
          }));
          return {
            ...rule,
            productCode,
            triggerTypeList: [],
            conditions: updatedConditions,
          };
        }
        return rule;
      })
    );

    // 获取产品详情
    if (productCode) {
      fetchProductDetail(productCode, ruleId);
    }
  };

  // 处理触发类型变化
  const handleTriggerTypeChange = (ruleId: string, conditionId: string, triggerType: string) => {
    setTriggerRules(
      triggerRules.map(rule => {
        if (rule.id === ruleId) {
          return {
            ...rule,
            conditions: rule.conditions.map(condition => {
              if (condition.id === conditionId) {
                return { ...condition, type: triggerType, fun: '' }; // 清空功能选择
              }
              return condition;
            }),
          };
        }
        return rule;
      })
    );
  };

  // 生成表达式（与旧代码保持一致）
  const generateExpression = (conditions: TriggerCondition[]) => {
    return conditions
      .map((condition, index) => {
        // 确保所有字段都有值才生成表达式
        if (!condition.type || !condition.fun || !condition.condition || !condition.val) {
          return '';
        }
        const expr = `${condition.type}.${condition.fun}${condition.condition}${condition.val}`;
        if (index < conditions.length - 1) {
          return `${expr} ${condition.con || 'or'} `;
        }
        return expr;
      })
      .filter(expr => expr) // 过滤掉空表达式
      .join('');
  };

  // 提交表单
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();

      // 验证触发规则数据
      for (const rule of triggerRules) {
        if (!rule.productCode) {
          window.$message.error('请选择设备');
          return;
        }

        for (const condition of rule.conditions) {
          if (!condition.type || !condition.fun || !condition.condition || !condition.val) {
            window.$message.error('请完善触发条件配置');
            return;
          }
        }
      }

      setLoading(true);

      const conditionReqs = triggerRules.map(rule => {
        const conditionContent = generateExpression(rule.conditions);
        console.log('生成的条件表达式:', conditionContent);
        return {
          productCode: rule.productCode,
          conditionType: 'expression',
          conditionContent,
        };
      });

      const submitData = {
        id: ruleId,
        perfectMatchMode: values.perfectMatchMode,
        silencePeriod: values.silencePeriod,
        alarmRuleInfoId: alarmRuleInfoId || ruleId, // 使用传入的告警规则ID
        conditionReqs,
      };

      console.log('提交触发规则数据:', submitData);
      console.log('ruleId:', ruleId);
      console.log('alarmRuleInfoId:', alarmRuleInfoId);

      const res = await editRulesContentApi(submitData);
      if (res.success) {
        window.$message.success('编辑触发规则成功');
        onSuccess?.(res.data?.ruleId);
        onClose();
      } else {
        window.$message.error(res.errorMsg || '编辑触发规则失败');
      }
    } catch (error) {
      console.error('提交失败:', error);
      window.$message.error('提交失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <ADrawer
      title="编辑触发规则"
      width={1000}
      open={open}
      onClose={onClose}
      footer={
        <div className="flex justify-end space-x-2">
          <AButton onClick={onClose}>取消</AButton>
          <AButton type="primary" loading={loading} onClick={handleSubmit}>
            确认
          </AButton>
        </div>
      }
    >
      <AForm form={form} layout="vertical">
        <AForm.Item
          label={
            <div className="flex items-center space-x-2">
              <span>静默时间</span>
              <span className="text-xs text-orange-600 font-normal">
                ⚠️
                已配置静默时间，则规则触发后发送告警，在设定的时间范围内将不再重复发送告警信息。超出设定时间后会重新开始，可合并发送告警。
              </span>
            </div>
          }
          name="silencePeriod"
          rules={[{ required: true, message: '请输入静默时间' }]}
        >
          <AInput placeholder="请输入静默时间" addonAfter="秒" type="number" />
        </AForm.Item>

        <AForm.Item
          label="执行限制"
          name="perfectMatchMode"
          rules={[{ required: true, message: '请选择执行限制' }]}
        >
          <ARadio.Group>
            <ARadio value={0}>满足任意条件执行</ARadio>
            <ARadio value={1}>满足全部条件执行</ARadio>
          </ARadio.Group>
        </AForm.Item>

        <div className="space-y-4">
          {triggerRules.map((rule, ruleIndex) => (
            <ACard
              key={rule.id}
              title={`启动规则 ${ruleIndex + 1}`}
              size="small"
              styles={{
                header: {
                  backgroundColor: '#f8f9fa',
                  borderBottom: '1px solid #e9ecef',
                },
              }}
              extra={
                triggerRules.length > 1 && (
                  <ATooltip title="删除规则">
                    <AButton
                      type="text"
                      danger
                      icon={<DeleteOutlined />}
                      onClick={() => deleteTriggerRule(rule.id)}
                    />
                  </ATooltip>
                )
              }
            >
              <AForm.Item label="设备" required>
                <ASelect
                  placeholder="请选择设备"
                  value={rule.productCode}
                  onChange={value => updateRuleProduct(rule.id, value)}
                  options={productOptions}
                />
              </AForm.Item>

              <div className="space-y-4">
                {rule.conditions.map(condition => (
                  <div
                    key={condition.id}
                    className="relative border border-gray-200 rounded-lg p-4 bg-gray-50 shadow-sm"
                  >
                    {/* 逻辑关系 - 左上角 */}
                    <div className="absolute top-2 left-2">
                      <div className="flex items-center space-x-2">
                        <span className="text-4 text-gray-500">关系:</span>
                        <ARadio.Group
                          value={condition.con}
                          onChange={e =>
                            updateCondition(rule.id, condition.id, 'con', e.target.value)
                          }
                          buttonStyle="solid"
                          size="small"
                        >
                          <ARadio.Button value="or">OR</ARadio.Button>
                          <ARadio.Button value="and">AND</ARadio.Button>
                        </ARadio.Group>
                      </div>
                    </div>

                    {/* 删除按钮 - 右上角 */}
                    {rule.conditions.length > 1 && (
                      <div className="absolute top-2 right-2">
                        <ATooltip title="删除条件">
                          <AButton
                            type="text"
                            danger
                            size="small"
                            icon={<DeleteOutlined />}
                            onClick={() => deleteCondition(rule.id, condition.id)}
                            className="hover:bg-red-50"
                          />
                        </ATooltip>
                      </div>
                    )}

                    {/* 条件配置区域 */}
                    <div className="pt-10">
                      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                        <div>
                          <label className="block text-sm font-medium text-gray-700 mb-1">
                            触发方式
                          </label>
                          <ASelect
                            placeholder="请选择触发方式"
                            value={condition.type}
                            onChange={value =>
                              handleTriggerTypeChange(rule.id, condition.id, value)
                            }
                            options={rule.triggerTypeList.map(item => ({
                              label: item.label,
                              value: item.value,
                            }))}
                            className="w-full"
                          />
                        </div>

                        <div>
                          <label className="block text-sm font-medium text-gray-700 mb-1">
                            功能
                          </label>
                          <ASelect
                            placeholder="请选择功能"
                            value={condition.fun}
                            onChange={value => updateCondition(rule.id, condition.id, 'fun', value)}
                            options={
                              condition.type
                                ? rule.triggerTypeList.find(item => item.value === condition.type)
                                    ?.triggerArr || []
                                : []
                            }
                            disabled={!condition.type}
                            className="w-full"
                          />
                        </div>

                        <div>
                          <label className="block text-sm font-medium text-gray-700 mb-1">
                            判断条件
                          </label>
                          <ASelect
                            placeholder="请选择判断条件"
                            value={condition.condition}
                            onChange={value =>
                              updateCondition(rule.id, condition.id, 'condition', value)
                            }
                            options={conditionOptions}
                            className="w-full"
                          />
                        </div>

                        <div>
                          <label className="block text-sm font-medium text-gray-700 mb-1">
                            预设值
                          </label>
                          <AInput
                            placeholder="请输入预设值"
                            value={condition.val}
                            onChange={e =>
                              updateCondition(rule.id, condition.id, 'val', e.target.value)
                            }
                            className="w-full"
                          />
                        </div>
                      </div>
                    </div>
                  </div>
                ))}

                <AButton
                  type="dashed"
                  icon={<PlusOutlined />}
                  onClick={() => addCondition(rule.id)}
                  className="w-full"
                >
                  添加条件
                </AButton>
              </div>

              {rule.conditions.length > 0 && (
                <div className="mt-3 p-2 bg-gray-50 rounded">
                  <span className="text-sm text-gray-600">
                    表达式: {generateExpression(rule.conditions)}
                  </span>
                </div>
              )}
            </ACard>
          ))}

          <AButton
            type="dashed"
            icon={<PlusOutlined />}
            onClick={addTriggerRule}
            className="w-full"
          >
            增加启动规则
          </AButton>
        </div>
      </AForm>
    </ADrawer>
  );
};

export default EditTriggerRulesDrawer;
